package com.xiashitech.agent.instrumentation.base.exporter.inst;

import com.xiashitech.agent.dns.CustomDns;
import okhttp3.Dns;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

public class XSBalanceDns implements Dns {
    @Override
    public List<InetAddress> lookup(String hostname) throws UnknownHostException {
        System.out.println(" =============================  XSBalanceDns called  ============ hostname: " + hostname);
        if (hostname == null) {
            throw new UnknownHostException("hostname == null");
        } else {
            try {
                List<InetAddress> mInetAddressesList = new ArrayList<>();
                InetAddress inetAddress = CustomDns.getInstance().getOneAddress(hostname);
                if(inetAddress != null) {
                    System.out.println(" XSBalanceDns lookup, getOneAddress, hostname: " + hostname + ", " + inetAddress.getHostAddress());
                    mInetAddressesList.add(0, inetAddress);
                    return mInetAddressesList;
                }
                // 引入自定义的域名解析
                InetAddress[] mInetAddresses = CustomDns.getInstance().getDnsRealIps(hostname);
                if(mInetAddresses == null) {
                    System.out.println(" XSBalanceDns lookup, can't get custom ip, hostname: " + hostname);
                    mInetAddresses = InetAddress.getAllByName(hostname);
                }
                for (InetAddress address : mInetAddresses) {
                    System.out.println(" ==== XSBalanceDns address: " + address.getHostAddress());
                    if (address instanceof Inet4Address) {
                        mInetAddressesList.add(0, address);
                    } else {
                        mInetAddressesList.add(address);
                    }
                }
                return mInetAddressesList;
            } catch (NullPointerException var4) {
                UnknownHostException unknownHostException = new UnknownHostException("Broken system behaviour");
                unknownHostException.initCause(var4);
                throw unknownHostException;
            }
        }
    }
}
